package com.huarui.action.service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;
import org.ewaf.framework.model.ListModel;
import org.ewaf.framework.service.BaseService;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.TransactionCallback;

import com.huarui.action.dao.IActionDao;
import com.huarui.initial.util.InitialErrorsEnum;
import com.huarui.initial.util.InitialVO;
import com.huarui.permission.dataobject.Action;
import com.huarui.saleInvoice.util.SaleInvoiceMessageEnum;
import com.huarui.user.model.SessionMessage;

public class ActionService extends BaseService {
	private final static Logger logger = Logger.getLogger(ActionService.class);
	private IActionDao getDao(){
		return (IActionDao) dao;
	}
	public Map<String,Object> save(final Action action){
		final Map<String,Object> resultMap=new HashMap<String, Object>();
		// 修改数据
		try {
			transactionTemplate.execute(new TransactionCallback() {
				@Override
				public Object doInTransaction(TransactionStatus status){
					if(action.getId()!=null){
						getDao().update(action);
					}else{
						getDao().create(action);
					}
					resultMap.put("action", action);
					return null;
				}
			});
		} catch (Exception e) {
			logger.error("保存action出错",e);
			resultMap.put(SaleInvoiceMessageEnum.SUCCESS.getMsg(), SaleInvoiceMessageEnum.ERROR_MSG_DATABASE.getMsg());
			return resultMap;
		}
		resultMapInfo(resultMap);
		return resultMap;
	}
	private void resultMapInfo(Map<String,Object> resultMap){
		if(!resultMap.containsKey(SaleInvoiceMessageEnum.SUCCESS.getMsg())){
			resultMap.put(SaleInvoiceMessageEnum.SUCCESS.getMsg(),SaleInvoiceMessageEnum.RESULT_TYPE_SUCCESS.getMsg());
		}
	}
	@SuppressWarnings("unchecked")
	public List<Map> pagingByCondition(ListModel lm, Map map) {
		Integer total = getDao().getCountByConditions(map);
		lm.setTotal(total);
		map.put("listModel", lm);
		List result = this.getDao().getListByConditions(map);
		lm.setResult(result);
		return result;
	}
	
	public Map<String,Object> getActionById(Integer id,SessionMessage sm) {
		Map<String,Object> resultMap=new HashMap<String, Object>();
		try {
			Action vo = (Action) getDao().getById(id);
			resultMap.put("data", vo);
		} catch (Exception e) {
			logger.error("根据id获得Action出错",e);
			resultMap.put(InitialErrorsEnum.SUCCESS.getMsg(),InitialErrorsEnum.ERROR_MSG_DATABASE.getMsg());
			return resultMap;
		}
		resultMap.put("userId", sm.getUserId());
		resultMap.put(InitialErrorsEnum.SUCCESS.getMsg(), InitialErrorsEnum.RESULT_TYPE_SUCCESS.getMsg());
		return resultMap;
	}
}
